package com.yanyilu.qiubite.service;

import com.yanyilu.qiubite.entity.AdminUser;
import com.yanyilu.qiubite.entity.Spot;
import com.yanyilu.qiubite.jpa.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class SpotService {
    @Autowired
    AdminUserJpa adminUserJpa;

    @Autowired
    StoryJpa storyJpa;
    @Autowired
    SpotJpa spotJpa;
    @Autowired
    PartJpa partJpa;
    @Autowired
    StorylineJpa storylineJpa;

    public Page<Spot> getList(Example<Spot> example, Pageable pageable) {
        return spotJpa.findAll(example,pageable);
    }

    public Spot findByAppId(String appId) {
        return spotJpa.findByAppId(appId);
    }

    @Transactional
    public void addSpot(Spot spot, String userName, String password) {
        spotJpa.save(spot);
        AdminUser adminUser = new AdminUser();
        adminUser.setUserName(userName);
        adminUser.setPassword(password);
        adminUser.setRole(1);
        adminUser.setSpotId(spot.getSpotId());
        adminUserJpa.save(adminUser);
        System.out.println(adminUser.getRole());
    }

    public void updateSpot(Spot spot) {
        spotJpa.save(spot);
    }

    //删除景区
    @Transactional
    public void spotDelete(Integer spotId){
        spotJpa.deleteById(spotId);
        adminUserJpa.deleteBySpotId(spotId);
        storyJpa.deleteBySpotId(spotId);
        List<Integer> storyIds = storyJpa.findStoryBySpotId(spotId);
        if(storyIds.size() > 0){
            partJpa.deleteByStoryIds(storyIds);
            List<Integer> partIds = partJpa.selectPartIdsByStoryIds(storyIds);
            if(partIds.size() > 0){
                storylineJpa.deleteByPartIds(partIds);
            }
        }
    }
}
